#!/usr/bin/env python
# -*- coding: utf-8 -*-

import struct

class StructProtocol:
    old_pack_data = ''
    headerData = None

    def pack(self, headData, bodyData):
        ret = struct.pack(self.headerFmt, headData[0], headData[1], headData[2], headData[3])
        ret = ret + bodyData
        return ret

    def __init__(self, hF=u'!iHH16s'):
        self.headerFmt = hF

    def putData(self, data):
        self.old_pack_data = self.old_pack_data + data

    def getOnce(self):
        if len(self.old_pack_data) < self.getHeaderLen():
            return None
        headerData = struct.unpack(self.headerFmt, self.old_pack_data[0:self.getHeaderLen()])
        if headerData[0]+self.getHeaderLen() > len(self.old_pack_data):
            return None
        else:
            bodyData = self.old_pack_data[self.getHeaderLen():self.getHeaderLen()+headerData[0]]
            self.old_pack_data = self.old_pack_data[self.getHeaderLen()+headerData[0]:]
            ret = {
                u"head": headerData,
                u"body": bodyData
            }
            return ret

    def getHeaderLen(self):
        return struct.calcsize(self.headerFmt)

    def GetBodyLen(self, data):
        return struct.unpack(self.headerFmt, data)[0]

    def GetHeader(self, data):
        return struct.unpack(self.headerFmt, data)


    def UnpackAll(self, data):
        return data

    def UnpackAll(self, data):
        self.old_pack_data = self.old_pack_data + data
        count = 0
        retList = []
        while 1:
            if len(self.old_pack_data) < self.getHeaderLen():
                return count, retList
            else:
                headerData = struct.unpack(self.headerFmt, self.old_pack_data[0:self.getHeaderLen()])
                if headerData[0]+self.getHeaderLen() > len(self.old_pack_data):
                    return count, retList
                else:
                    bodyData = self.old_pack_data[self.getHeaderLen():self.getHeaderLen()+headerData[0]]
                    self.old_pack_data = self.old_pack_data[self.getHeaderLen()+headerData[0]:]
                    count += 1
                    tempDict = {
                        u"head": headerData,
                        u"body": bodyData
                    }
                    retList.append(tempDict)